const http = require("http");
const data = require("data");


// console.log(data);
const app = http.createServer((req,res)=>{
    let newUrl = new URL(req.url,"http://localhost:8080");
    let str = `<a href="/" style="text-decoration: none;border: 1px solid;border-radius: 5px;padding:0 5px;">←</a>`
    switch(newUrl.pathname){
        case "/":
            str = `<ul>`;
            data.forEach((item)=>{
                str += `<li><a href="/detail?id=${item.id}">${item.newsTitle}</a></li>`;
            })
            str += `</ul>`;
            res.setHeader("content-type","text/html;charset=utf-8;");
            res.end(str);
            break;
        case "/detail":
            let id = newUrl.searchParams.get("id");
            let obj = data.find(item=>item.id === id);
            str += `
            <h2>${obj.newsTitle}</h2>
            <p>${obj.newsContent}</p>
            `;
            res.setHeader("content-type","text/html;charset=utf-8;");
            res.end(str);
            break;
        default:
            res.end("404");
    }


})



app.listen(8080,()=>{
    console.log("80端口开启~");
})